package com.edu.koudingmusic.activities;

import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.edu.koudingmusic.BaseActivity;
import com.edu.koudingmusic.BaseApplication;
import com.edu.koudingmusic.R;
import com.edu.koudingmusic.entities.Mp3Info;
import com.edu.koudingmusic.entities.SearchResult;
import com.edu.koudingmusic.services.PlayService;
import com.edu.koudingmusic.tools.Constant;
import com.edu.koudingmusic.tools.DownloadUtils;
import com.edu.koudingmusic.tools.MediaUtils;
import com.edu.koudingmusic.tools.SearchMusicUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import douzi.android.view.DefaultLrcBuilder;
import douzi.android.view.ILrcBuilder;
import douzi.android.view.ILrcView;
import douzi.android.view.LrcRow;
import douzi.android.view.LrcView;

public class MusicPlayActivity extends BaseActivity implements View.OnClickListener, SeekBar.OnSeekBarChangeListener {

    private static final String TAG = "MusicPlayActivity";
    // 设置更新播放时间
    private static final int UPDATE_TIME = 0x10;
    private static final int UPDATE_LRC = 0x20;
    private TextView mMusicTitle;
    private ImageView mMusicAlbum;
    private SeekBar mMusicSeekbar;
    private TextView mMusicStartTime;
    private TextView mMusicEndTime;
    private ImageView mMusicMode;
    private ImageView mMusicPre;
    private ImageView mMusicPause;
    private ImageView mMusicNext;
    //private ArrayList<Mp3Info> mMp3Infos;

    private ArrayList<View> mViews;

    private static MyHandler sHandler;
    private ViewPager mViewPager;
    private ImageView mMusicFavorite;
    private BaseApplication mApp;
    private LrcView mLrcView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_play);

        mApp = (BaseApplication) getApplication();
        initViews();
        sHandler = new MyHandler(this);
        mViews = new ArrayList<>();
        initViewPager();
    }

    // seekbar 的拖动事件
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (fromUser) {
            mPlayService.pause();
            mPlayService.seekTo(progress);
            mPlayService.start();
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }


    static class MyHandler extends Handler {

        // 用软引用
        private final WeakReference<MusicPlayActivity> mWeakReference;

        public MyHandler(MusicPlayActivity musicPlayActivity) {
            mWeakReference = new WeakReference<>(musicPlayActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            MusicPlayActivity musicPlayActivity = mWeakReference.get();
            if (musicPlayActivity != null) {
                switch (msg.what) {
                    case UPDATE_TIME:
                        musicPlayActivity.mMusicStartTime.setText(MediaUtils.formatTime(msg.arg1));
                        break;

                    case UPDATE_LRC:
                        musicPlayActivity.mLrcView.seekLrcToTime((int)msg.obj);
                        break;
                    case DownloadUtils.SUCCESS_LRC:
                        musicPlayActivity.loadLRC(new File((String) msg.obj));
                        break;
                    case DownloadUtils.FAILED_LRC:
                        Toast.makeText(musicPlayActivity, "歌词下载失败", Toast.LENGTH_SHORT).show();
                        break;

                    default:
                        break;
                }
            }
        }
    }

    private void initViewPager() {
        View albumView = getLayoutInflater().inflate(R.layout.album_image_layout, null);
        mMusicTitle = (TextView) albumView.findViewById(R.id.music_play_title);
        mMusicAlbum = (ImageView) albumView.findViewById(R.id.music_play_album);
        mViews.add(albumView);
        View lrc_layout = getLayoutInflater().inflate(R.layout.lrc_layout, null);
        mLrcView = ((LrcView) lrc_layout.findViewById(R.id.lrcView));
        //设置滚动事件
        mLrcView.setListener(new ILrcView.LrcViewListener() {
            @Override
            public void onLrcSeeked(int newPosition, LrcRow row) {
                if (mPlayService.isPlaying()){
                    mPlayService.seekTo((int)row.time);
                }
            }
        });
        mLrcView.setLoadingTipText("正在加载歌词");
        mLrcView.setBackgroundResource(R.mipmap.jb_bg);
        mLrcView.getBackground().setAlpha(150);
        mViews.add(lrc_layout);
        mViewPager.setAdapter(new MyPagerAdapter());
    }

    private void initViews() {
        mViewPager = (ViewPager) findViewById(R.id.viewpager);
        mMusicSeekbar = (SeekBar) findViewById(R.id.seekBar);
        mMusicStartTime = (TextView) findViewById(R.id.music_play_start_time);
        mMusicEndTime = (TextView) findViewById(R.id.music_play_end_time);
        mMusicMode = (ImageView) findViewById(R.id.music_play_mode);
        mMusicFavorite = (ImageView) findViewById(R.id.music_play_favorite);
        mMusicPre = (ImageView) findViewById(R.id.music_play_previous);
        mMusicPause = (ImageView) findViewById(R.id.music_play_pause);
        mMusicNext = (ImageView) findViewById(R.id.music_play_next);
        mMusicMode.setOnClickListener(this);
        mMusicFavorite.setOnClickListener(this);
        mMusicPre.setOnClickListener(this);
        mMusicPause.setOnClickListener(this);
        mMusicNext.setOnClickListener(this);
        mMusicSeekbar.setOnSeekBarChangeListener(this);
        // 同步歌曲
        //mMp3Infos = MediaUtils.getMp3Infos(this);
    }

    @Override
    public void publish(int progress) {

        // 这个方法在子线程中执行，不能根系ui 所以需要 handler
        //mMusicStartTime.setText(MediaUtils.formatTime(progress));
 /*       Message message = sHandler.obtainMessage(UPDATE_TIME);
        message.arg1 = progress;
        sHandler.sendMessage(message);
        mMusicSeekbar.setProgress(progress);*/

        sHandler.obtainMessage(UPDATE_TIME,progress).sendToTarget();
        mMusicSeekbar.setProgress(progress);
        sHandler.obtainMessage(UPDATE_LRC,progress).sendToTarget();
    }

    @Override
    public void change(int position) {
        if (this.mPlayService.isPlaying()) {
            mMusicPause.setImageResource(R.mipmap.pause);
        } else {
            mMusicPause.setImageResource(R.mipmap.play);
        }
        //Mp3Info mp3Info = mMp3Infos.get(position);

        // 同步歌曲
        Mp3Info mp3Info = mPlayService.getMp3Infos().get(position);
        Log.e(TAG, "change: 音乐播放默认的" + mp3Info);
        mMusicTitle.setText(mp3Info.getTitle());
        mMusicEndTime.setText(MediaUtils.formatTime(mp3Info.getDuration()));
        /*Bitmap albumImage = MediaUtils.getArtwork(this, mp3Info.getId(), mp3Info.getAlbumId(), true, false);
        mMusicAlbum.setImageBitmap(albumImage);*/
        mMusicAlbum.setImageResource(R.mipmap.music_album);
        mMusicSeekbar.setProgress(0);
        mMusicSeekbar.setMax((int) mp3Info.getDuration());

        // 模式
        switch (mPlayService.getPlay_Mode()) {
            case PlayService.PLAY_ORDER:
                mMusicMode.setImageResource(R.mipmap.order);
                mMusicMode.setTag(PlayService.PLAY_ORDER);

                break;
            case PlayService.PLAY_RANDOM:
                mMusicMode.setImageResource(R.mipmap.random);
                mMusicMode.setTag(PlayService.PLAY_RANDOM);
                break;
            case PlayService.PLAY_SINGLE:
                mMusicMode.setImageResource(R.mipmap.single);
                mMusicMode.setTag(PlayService.PLAY_SINGLE);
                break;
        }
        // 初始化收藏状态
        try {
            Mp3Info likeMp3Info = mApp.sDbUtils.findFirst(Selector.from(Mp3Info.class).where("mp3InfoId", "=", mp3Info.getMp3InfoId()));
            Log.e(TAG, "change: 音乐播放" + likeMp3Info);
            if (likeMp3Info != null) {
                if (likeMp3Info.getIsLike() == 1) {
                    Log.e(TAG, "change: 喜欢");
                    mMusicFavorite.setImageResource(R.mipmap.xin_hong);
                } else {
                    mMusicFavorite.setImageResource(R.mipmap.xin_bai);
                }
            } else {
                mMusicFavorite.setImageResource(R.mipmap.xin_bai);
            }

        } catch (DbException e) {
            e.printStackTrace();
        }

        // 歌词
        String songName = mp3Info.getTitle();
        String lrcPath = Environment.getExternalStorageDirectory()+ Constant.DIR_LRC+"/" +songName+".lrc";
        File lrcFile = new File(lrcPath);
        if (!lrcFile.exists()){
            // 下载
            SearchMusicUtils.getInstance().setListener(new SearchMusicUtils.OnSearchResultListener() {
                @Override
                public void onSearchResult(ArrayList<SearchResult> searchResults) {
                    SearchResult result = searchResults.get(0);
                    Log.e(TAG, "onSearchResult: "+result);
                    String url = Constant.BAIDU_URL+result.getUrl();
                    DownloadUtils.getInstance().downloadLrc(url,result.getMusicName(),sHandler);
                }
            }).search(songName+" "+mp3Info.getArtist(),1);
        }else {
            loadLRC(lrcFile);
        }
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.music_play_pause:
                if (mPlayService.isPlaying()) {
                    mMusicPause.setImageResource(R.mipmap.play);
                    mPlayService.pause();
                } else {
                    if (mPlayService.isPause()) {
                        mMusicPause.setImageResource(R.mipmap.player_btn_pause_normal);
                        mPlayService.start();
                    } else {
                        // 这边可以进记录
                        mPlayService.play(mPlayService.getCurrentPosition());
                    }
                }
                break;
            case R.id.music_play_favorite:
                // 喜爱收藏

              /*  DbManager db = x.getDb(mApp.getDaoConfig());
                Mp3Info mp3Info = mMp3Infos.get(mPlayService.getCurrentPosition());
                Mp3Info likeMp3Info = null;
                try {
                    Selector<Mp3Info> mp3InfoId = db.selector(Mp3Info.class).where("mp3InfoId", "=", mp3Info.getId());
                    likeMp3Info = db.findFirst(mp3InfoId.findFirst().getClass());
                } catch (DbException e) {
                    e.printStackTrace();
                }
                Log.e(TAG, "onClick: " + likeMp3Info);
                try {
                    if (likeMp3Info == null) {
                        mp3Info.setMp3InfoId(mp3Info.getId());
                        db.save(mp3Info);
                        Log.e(TAG, "onClick: save");
                        mMusicFavorite.setImageResource(R.mipmap.xin_hong);
                    } else {
                        db.deleteById(Mp3Info.class, likeMp3Info.getId());
                        Log.e(TAG, "onClick: delete");
                        mMusicFavorite.setImageResource(R.mipmap.xin_bai);
                    }
                } catch (DbException e) {
                    e.printStackTrace();
                }*/

                // xUitls jar
                //Mp3Info mp3Info = mMp3Infos.get(mPlayService.getCurrentPosition());
                // 同步
                Mp3Info mp3Info = mPlayService.getMp3Infos().get(mPlayService.getCurrentPosition());
                try {
                    Mp3Info likeMp3Info = mApp.sDbUtils.findFirst(Selector.from(Mp3Info.class).where("mp3InfoId", "=", getId(mp3Info)));
                    Log.e(TAG, "onClick: " + likeMp3Info);
                    if (likeMp3Info == null) {
                        mp3Info.setMp3InfoId(mp3Info.getId());
                        mp3Info.setIsLike(1);
                        mApp.sDbUtils.save(mp3Info);
                        Log.e(TAG, "onClick: save");
                        mMusicFavorite.setImageResource(R.mipmap.xin_hong);
                    } else {
                        int isLike = likeMp3Info.getIsLike();
                        if (isLike == 1) {
                            likeMp3Info.setIsLike(0);
                            mMusicFavorite.setImageResource(R.mipmap.xin_bai);
                        } else {
                            likeMp3Info.setIsLike(1);
                            mMusicFavorite.setImageResource(R.mipmap.xin_hong);
                        }
                        mApp.sDbUtils.update(likeMp3Info, "isLike");
                        Log.e(TAG, "onClick: delete");

                    }
                } catch (DbException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.music_play_previous:
                mPlayService.prev();
                break;
            case R.id.music_play_next:
                mPlayService.next();
                break;
            case R.id.music_play_mode:
                int mode = (int) mMusicMode.getTag();
                switch (mode) {
                    case PlayService.PLAY_ORDER:
                        mMusicMode.setImageResource(R.mipmap.random);
                        mMusicMode.setTag(PlayService.PLAY_RANDOM);
                        mPlayService.setPlay_Mode(PlayService.PLAY_RANDOM);
                        Toast.makeText(this, "随机播放", Toast.LENGTH_SHORT).show();
                        break;
                    case PlayService.PLAY_RANDOM:
                        mMusicMode.setImageResource(R.mipmap.single);
                        mMusicMode.setTag(PlayService.PLAY_SINGLE);
                        mPlayService.setPlay_Mode(PlayService.PLAY_SINGLE);
                        Toast.makeText(this, "单曲循环", Toast.LENGTH_SHORT).show();
                        break;
                    case PlayService.PLAY_SINGLE:
                        mMusicMode.setImageResource(R.mipmap.order);
                        mMusicMode.setTag(PlayService.PLAY_ORDER);
                        mPlayService.setPlay_Mode(PlayService.PLAY_ORDER);
                        Toast.makeText(this, "顺序播放", Toast.LENGTH_SHORT).show();
                        break;
                }
                break;
            default:
                break;
        }

    }

    private long getId(Mp3Info mp3Info) {
        // 初始化收藏状态
        long id = 0;
        switch (mPlayService.getChangeList()) {
            case PlayService.MY_MUSIC_LIST:
                id = mp3Info.getId();
                break;
            case PlayService.MY_LIKE_MUSIC_LIST:
                id = mp3Info.getMp3InfoId();
                break;
            default:
                break;
        }
        return id;
    }

    class MyPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return mViews.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = mViews.get(position);
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            super.destroyItem(container, position, object);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.e(TAG, "onResume: 绑定服务");
        // 绑定服务
        bindPlayService();
    }

    @Override
    public void onPause() {
        super.onPause();
        // 解绑服务
        unBindPlayService();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    // 加载歌词
    private void loadLRC(File lrcFile){
        StringBuffer buf  = new StringBuffer(1024*10);
        char[] chars = new char[1024];
        try {
            BufferedReader bufr = new BufferedReader(new InputStreamReader(new FileInputStream(lrcFile)));
            int len = -1;
            while ((len=bufr.read(chars))!=-1){
                buf.append(chars,0,len);
            }
            bufr.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        ILrcBuilder builder = new DefaultLrcBuilder();
        List<LrcRow> rows =builder.getLrcRows(buf.toString());
        mLrcView.setLrc(rows);

    }
}
